import StringIO

class Properties:
	def __init__(self):
		self.__properties = dict()
		self.__order = list()
	
	def parse(self, string):
		stream = StringIO.StringIO(string)
		while True:
			line = stream.readline().strip()
			if line == "PROPS-END":
				break
			identifier, length = line.split(" ")
			assert identifier == "K"
			key = stream.read(int(length))
			stream.readline()
			identifier, length = stream.readline().split(" ")
			assert identifier == "V"
			value = stream.read(int(length))
			self.__properties[key] = value
			self.__order.append(key)
			stream.readline()
	
	def get_length(self):
		result = 0
		for key in self.__order:
			result += 2 # "K\s"
			result += len(str(len(key))) # number of key length
			result += 1 # "\n"
			result += len(key)
			result += 1 # "\n"
			result += 2 # "V\s"
			result += len(str(len(self.__properties[key]))) # number of value length
			result += 1 # "\n"
			result += len(self.__properties[key])
			result += 1 # "\n"
		result += 10 # "PROPS-END\n"
		return result
	
	def get_string(self):
		stream = StringIO.StringIO()
		for key in self.__order:
			stream.write("K " + str(len(key)) + "\n")
			stream.write(key + "\n")
			stream.write("V " + str(len(self.__properties[key])) + "\n")
			stream.write(self.__properties[key] + "\n")
		stream.write("PROPS-END\n")
		return stream.getvalue()
	
	def __get_count(self):
		return len(self.__properties)
	
	def __contains__(self, key):
		return self.__properties.has_key(key)
	
	def __getitem__(self, key):
		return self.__properties[key]
	
	def __setitem__(self, key, value):
		self.__properties[key] = value
	
	count = property(__get_count)

if __name__ == "__main__":
	properties = Properties()
	assert "hallo" not in properties
	properties["blub"] = "ding"
	assert "blub" in properties
